<template>
  <xdh-layout fixed :west="{width:'300px', split:true}">
    <xdh-panel slot="west"
               :fit="true"
               title="组织结构">
      <template slot="tool">
        <el-input size="mini" :clearable="true" placeholder="输入关键字进行过滤"
                  v-model="filterText">
        </el-input>
      </template>
      <el-tree
        :data="orgList"
        node-key="id"
        :highlight-current="true"
        :props="defaultProps"
        :check-strictly="true"
        :expand-on-click-node="false"
        :default-expanded-keys="defaultExpandedKeys"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
        v-loading="treeLoading"
        class="orgTree xdh-tree"
        ref="orgRef">
      </el-tree>
    </xdh-panel>

    <xdh-curd ref="curd"
              :filter="false"
              :collapsible="false"
              name="sysOrg"
              :model="model"
              :rules="rules"
              :mixin="mixin"
              :query="listQuery"
              :is-auto="false"
              model-key="pkValue"
              :handleType="'icon'"
              formLabelWidth="120px"
              :removeDisabled="removeDisabled"
              @on-error="errorList"
              @on-success="successList"
              :addable="false"
              :removable="false"
              :listTitle="`${model.parentName} 属下组织`">

      <!-- 数据列表 -->
      <template slot="table-columns"
                slot-scope="scope">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="dwmc" label="名称" min-width="100"></el-table-column>
        <el-table-column prop="dwjc" label="简称" min-width="100"></el-table-column>
        <el-table-column prop="dwms" label="单位描述" min-width="100"></el-table-column>
        <el-table-column prop="isDefault" label="是否总队业务支队" min-width="60">
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.zdywzd === '1'">是</el-tag>
            <el-tag size="mini" type="danger" v-else>否</el-tag>
          </template>
        </el-table-column>
        <!--<el-table-column prop="parentName" label="上级组织" min-width="100">-->
        <!--<template slot-scope="scope">-->
        <!--{{scope.row.parentName||'-'}}-->
        <!--</template>-->
        <!--</el-table-column>-->
      </template>

      <!-- 数据新增编辑弹窗 -->
      <template slot="dialog-form-items"
                slot-scope="prop">
        <el-form-item label="上级组织" prop="ssjdw">
          {{model.parentName}}
        </el-form-item>
        <!--<el-form-item label="单位名称" prop="name">-->
        <!--<el-input v-model="prop.model.name"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="单位简称" prop="dwjc">
          <el-input v-model="prop.model.dwjc"></el-input>
        </el-form-item>
        <el-form-item label="单位代码" prop="id">
          <el-input v-model="prop.model.id"></el-input>
        </el-form-item>
        <el-form-item label="单位描述" prop="dwms">
          <el-input type="textarea" :rows="2" v-model="prop.model.dwms"></el-input>
        </el-form-item>
        <el-form-item label="单位类型" prop="type">
          <el-select v-model="prop.model.dwType" placeholder="请选择">
            <el-option
              v-for="item in orgType"
              :key="item.name"
              :label="item.label"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否总队业务支队">
          <el-radio-group v-model="prop.model.zdywzd">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
    </xdh-curd>

  </xdh-layout>
</template>
<style type="text/scss" lang="scss" scoped>
  .orgTree {
    display: table;
    width: 100%;
  }
</style>

<script>
  import XdhLayout from '../../widgets/xdh-layout'
  import XdhCurd from '../../widgets/xdh-curd'
  import xdhPanel from '../../widgets/xdh-panel'
  import sysOrg from '../../base/mixin/sys-org'
  import {clone} from '../../utils/convert'
  import {getOrgTree, updateOrgTreeStore} from '../../helper/before'
  import sysDictionary from '../../base/mixin/sys-dictionary'
  import {mapState} from 'vuex'

  export default {
    components: {
      XdhCurd,
      xdhPanel,
      XdhLayout
    },
    mixins: [sysOrg, sysDictionary],
    computed: {
      ...mapState({
        orgTree: state => state.sysOrgTree.orgTree || null
      })
    },
    data() {
      return {
        mixin: sysOrg,
        defaultExpandedKeys: [],
        orgList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        selectNode: {},
        orgType: [{
          name: '',
          label: '请选择'
        }],
        model: {
          ssjdw: '', // 上级组织ID
          parentName: '', // 上级组织名称
          id: '',
          dwType: '',
          orgId: '', // 编号
          dwms: '', // 组织描述
          // name: '', // 组织名称
          isDefault: false, // 是否默认组织
          zdywzd: '0'  // 是否总队业务支队
        },
        listQuery: {},
        hasAddReload: false, // 添加节点操作后的列表加载
        rules: {
          name: [{
            required: true,
            message: '必需填写组织名称'
          }],
          id: [{
            required: true,
            message: '必需填写组织代码'
          }]
        },
        filterText: '',
        treeLoading: false
      }
    },
    methods: {
      /**
       * 组织筛选
       */
      filterNode(value, data) {
        if (!value) return true
        return data[this.defaultProps.label].indexOf(value) !== -1
      },
      /**
       * 点击左侧菜单树选择
       * @param data
       * @param node
       * @param r
       */
      nodeClick(data, node, r) {
        this.selectNode = data
        this.listQuery = {}
        this.listQuery.keyword = data.pid
        this.model.ssjdw = data.pid
        this.model.parentName = data.label
        this.$nextTick(() => {
          this.$refs.curd.reload()
        })
      },
      /**
       * 默认选中和展开第一个树节点
       */
      defaultSetCurrentTree(noLoadKey = false) {
        this.$nextTick(() => {
          let currentKey = this.orgList[0]
          if (!noLoadKey) {
            currentKey = this.selectNode
          }
          this.$refs['orgRef'].setCurrentKey(currentKey.id)
          this.defaultExpandedKeys = [currentKey.id]
          this.nodeClick(currentKey)
          this.loading = false
        })
      },
      /**
       * 查询组织树
       */
      queryTree(isLoadCurrentKey = true) {
        if (!this.orgTree) {
          this.treeLoading = true
          getOrgTree().then(d => {
            this.orgList = clone(d)
            if (this.orgList.length > 0) {
              this.defaultSetCurrentTree(isLoadCurrentKey)
            }
            this.treeLoading = false
          })
        } else {
          this.orgList = clone(this.orgTree)
          if (this.orgList.length > 0) {
            this.defaultSetCurrentTree(isLoadCurrentKey)
          }
        }
      },
      errorList(type, data) {
        this.$message({
          type: 'error',
          message: data.msg
        })
      },
      /**
       * 列表数据请求成功回调
       */
      successList(type, data) {
        if (this.hasAddReload && type === 'fetch') {
          // todo: 添加操作后的列表查询 添加成功接口未返回新数据主键的退选处理,新增接口调整后 再处理优化
          if (this.selectNode.list.length > 0) {
            // this.$refs.orgRef.insertBefore
          } else {
            this.$refs.orgRef.updateKeyChildren(this.selectNode.pkValue, data.list)
          }
          this.hasAddReload = false
          // 更新OrgTreeStore 状态
          updateOrgTreeStore(this.orgList[0])
        }

        if (type === 'add') {
          this.$refs.curd.reload()
          this.hasAddReload = true // 是否是添加后的加载
        }

        if (type === 'remove') {
          this.$refs.orgRef.remove(data.pkValue)
          // 更新OrgTreeStore 状态
          updateOrgTreeStore(this.orgList[0])
        }

        if (type === 'update') {
          let childrenList = this.selectNode.list || []
          this.$refs.orgRef.updateKeyChildren(this.selectNode.pkValue, childrenList.map(item => {
            if (item.pkValue === data.pkValue) {
              return data
            }
            return item
          }))
          // 更新OrgTreeStore 状态
          updateOrgTreeStore(this.orgList[0])
        }
      },
      removeDisabled(row) {
        return row.isDefault
      }
    },
    watch: {
      filterText(val) {
        this.$refs.orgRef.filter(val)
      }
    },
    mounted() {
      this.getDictList({dictValue: 'dwlx'}).then(res => {
        this.orgType = res
      })
    },
    created() {
      this.queryTree()
    }
  }
</script>

